const { request } = require('express');
var express = require('express');
var router = express.Router();
var { aesEncrypt, keys, checkUsername } = require("../utils");
var { CustomerModel } = require('../utils/model')

/* GET home page. */
// router.get('/', function (req, res, next) {
//   res.render('index', { title: 'Express' });
// });

router.get('/', function (req, res, next) {
  res.render('index',
    {
      // title: '超级管家',
      username: req.session.username || '',
      // mobile: '',

    });
  console.log(req.session.username);
});

// 退出登录
router.get('/logout', (req, res) => {
  req.session.destroy(() => {
    res.redirect('/') //重定向
  })
})
//员工管理
router.get('/staff_insert', (req, res) => {
  checkUsername(req, res, username => {
    res.render('staff_insert',{username})
  })
})






// 客户预定

router.get('/test', (req, res) => {
  res.send('这是一个测试。。。。')
})
router.get('/newkehu', (req, res) => {
  checkUsername(req, res, username => {
    res.render('newkehu', {
      username
    })
  })

})


//客户注册
router.post('/newkehu/submit', (req, res) => {
  var body = req.body;

  console.log(body)
  CustomerModel.findOne({
    customer: body.customer
  }).then(data => {
    if (data) {
      res.send(`<script>alert('您被限制消费，无法办理入住');location.href='/newkehu'</script>`)
    } else {
      body.time = new Date();
      CustomerModel.insertMany(body)

        .then(result => {
          res.send(`<script>alert('恭喜你,办理入住成功');location.href='/kehulist' </script>`)
        }).catch(err => {
          res.send(`<script>alert('办理入住失败');location.href='/newkehu' </script>`)
        })
    }
  })
})
//客户列表渲染
router.get('/kehulist', (req, res) => {
  checkUsername(req, res, username => {
    CustomerModel.find({})
      .then(data => {

        res.render('kehulist', {
          data,
          username
        })
        // res.send(data)
      })
  })



})
//客户退房
router.get('/removeone', (req, res) => {

  CustomerModel.deleteOne({
    _id: req.query._id
  }).then(result => {
    res.json({
      code: 200,
      result,
      msg: '退房成功'
    })
  })
})

//客户换房
router.get('/updateone', (req, res) => {
  var query = req.query
  console.log(query);
  CustomerModel.updateMany({
    _id: req.query._id
  }, {
    $set: {
      roomtype: query.roomtype
    }
  }).then(result => {
    res.json({
      code: 200,
      result,
      msg: '换房成功'
    })
  })
})






module.exports = router;
